package com.ruoyi.novel.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.novel.domain.Integral;
import com.ruoyi.novel.domain.Order;
import com.ruoyi.novel.domain.Vip;
import com.ruoyi.novel.service.IOrderService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.novel.domain.User;
import com.ruoyi.novel.service.IUserService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 用户信息Controller
 *
 * @author 张三
 * @date 2025-04-18
 */
@RestController
@RequestMapping("/novel/user")
public class UserController extends BaseController
{
    @Autowired
    private IUserService userService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询用户信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(User user)
    {
        if(user.getReferrer() != null && user.getReferrer() == 1){
            Long userId = SecurityUtils.getUserId();
            user.setReferrer(Math.toIntExact(userId));
        }
        startPage();
        List<User> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 导出用户信息列表
     */
    @PreAuthorize("@ss.hasPermi('novel:user:export')")
    @Log(title = "用户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, User user)
    {
        List<User> list = userService.selectUserList(user);
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        util.exportExcel(response, list, "用户信息数据");
    }

    /**
     * 获取用户信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('novel:user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        AjaxResult result = success();
        User user = userService.selectUserById(id);
        result.put("data",user);
        result.put("referrer",userService.getById(user.getReferrer()));
        return result;
    }

    /**
     * 新增用户信息
     */
    @PreAuthorize("@ss.hasPermi('novel:user:add')")
    @Log(title = "用户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody User user)
    {
        RegisterBody body = new RegisterBody();
        body.setUsername(user.getPhone());
        body.setPassword(user.getPhone());
        AjaxResult result = userService.register(body);
        if((boolean) result.get("regFlag")){
            SysUser sysUser = (SysUser) result.get("sysUser");
            sysUser.setUserId(Long.valueOf(user.getId()));
            sysUser.setPhonenumber(user.getPhone());
            sysUser.setRoleIds(new Long[]{2L});
            sysUserService.updateUser(sysUser);
            user.setId(Math.toIntExact(sysUser.getUserId()));
            user.setLevelTime(new Date());
            if(user.getReferrer() != null && user.getReferrer() == 1){
                Long userId = SecurityUtils.getUserId();
                User user1 = userService.getById(userId);
                if(user1 != null){
                    List<String> list = new ArrayList<>();
                    list.addAll(Arrays.asList(user1.getAncestors().split(",")));
                    String id = String.valueOf(user1.getId());
                    if(list.isEmpty() || list == null){
                        list = new ArrayList<>();
                        list.add("0");
                        list.add(id);
                    }else {
                        list.add(id);
                    }
                    String ancestors = String.join(",", list);
                    user.setReferrer(Math.toIntExact(userId));
                    user.setAncestors(ancestors);
                }else {
                    user.setReferrer(0);
                }
            }
            return toAjax(userService.insertUser(user));
        }else {
            return AjaxResult.error((String) result.get("msg"));
        }
    }

    /**
     * 修改用户信息
     */
    @PreAuthorize("@ss.hasPermi('novel:user:edit')")
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody User user)
    {
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户信息
     */
    @PreAuthorize("@ss.hasPermi('novel:user:remove')")
    @Log(title = "用户信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(userService.deleteUserByIds(ids));
    }

    /**
     * 用户充值
     * @param user
     * @return
     */
    @Transactional
    @PostMapping("/userRecharge")
    public AjaxResult userRecharge(@RequestBody User user){
        Order order = new Order();
        order.setMode(user.getMode());
        order.setType(1);
        order.setUserId(user.getId());
        order.setPhone(user.getPhone());
        order.setIntegralId(user.getIntegralId());
        order.setVipId(user.getVipId());
        AjaxResult result = orderService.createOrder(order);
        Integer code = (Integer) result.get("code");
        if(code == 500){
            return result;
        }
        if(order.getMode() == 0){
            //会员订单
            Vip vip = (Vip) result.get("vip");
            if(vip == null){
                return AjaxResult.error("会员信息有误");
            }
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", user.getId()).set("level",vip.getLevel());
            if(vip.getLevel() == 1){
                updateWrapper.setSql("level_time = DATE_ADD(NOW(), INTERVAL 1 DAY)");
            }else if(vip.getLevel() == 2){
                updateWrapper.setSql("level_time = DATE_ADD(NOW(), INTERVAL 1 MONTH)");
            }else if(vip.getLevel() == 3){
                updateWrapper.setSql("level_time = DATE_ADD(NOW(), INTERVAL 1 YEAR)");
            }
            userService.update(updateWrapper);
        }else if(order.getMode() == 1){
            //充值订单
            Integral integral = (Integral) result.get("integral");
            if(integral == null){
                return AjaxResult.error("充值信息有误");
            }
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", user.getId()).setSql("money = money +"+ integral.getIntegral());
            userService.update(updateWrapper);
        }
        return AjaxResult.success();
    }


}
